package com.zw.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.zw.config.AliyunConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * @author ：zhangwu
 * @email : zhangwu204@163.com
 * @date ：2025/4/14 16:38
 */
@Component
public class OssUploader {

    public static String UPLOAD_SUB_PREFIX = "medical_data_security_project";
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private AliyunConfig aliyunConfig;

    /**
     * 批量上传PDF文件（最多10个）
     * @param files MultipartFile数组
     * @return 成功上传的文件URL列表
     */
    public List<String> uploadPdfFiles(MultipartFile[] files) {
        // 1. 校验文件数量
        if (files.length > 10) {
            throw new IllegalArgumentException("一次最多上传10个PDF文件");
        }

        List<String> uploadedUrls = new ArrayList<>();
        for (MultipartFile file : files) {
            // 2. 校验文件类型
            validatePdfFile(file);

            try (InputStream inputStream = file.getInputStream()) {
                String url = uploadFile(inputStream, file.getOriginalFilename());
                uploadedUrls.add(url);
            } catch (IOException e) {
                throw new RuntimeException("文件读取失败: " + file.getOriginalFilename(), e);
            }
        }
        return uploadedUrls;
    }

    /**
     * 私有方法：上传单个文件到OSS
     */
    private String uploadFile(InputStream inputStream, String originalFilename) {
        // 生成唯一文件名逻辑保持不变
        String today = sdf.format(new Date());
        String fileName = UPLOAD_SUB_PREFIX + "/" + today + "/" + UUID.randomUUID() + ".pdf"; // 强制后缀为pdf

        // 上传文件到OSS
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunConfig.getBucketName(), fileName, inputStream);
        aliyunConfig.oSSClient().putObject(putObjectRequest);
        return fileName;
    }

    /**
     * 校验是否为合法PDF文件
     */
    private void validatePdfFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        // 校验扩展名
        String fileExtension = getFileExtension(originalFilename);
        if (!"pdf".equalsIgnoreCase(fileExtension)) {
            throw new IllegalArgumentException("仅支持PDF文件，无效的扩展名: " + originalFilename);
        }

        // 校验MIME类型
        if (!"application/pdf".equalsIgnoreCase(file.getContentType())) {
            throw new IllegalArgumentException("文件类型不匹配: " + originalFilename);
        }
    }

    /**
     * 获取文件后缀（小写）
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }
}

